package com.violet.service.app.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.violet.domain.po.Category;
import com.violet.domain.po.Product;
import com.violet.domain.vo.app.ACategoryVo;
import com.violet.mapper.CategoryMapper;
import com.violet.mapper.ProductMapper;
import com.violet.service.app.ACategoryService;
import com.violet.utils.TransitionUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Stream;

@Service
@RequiredArgsConstructor
public class ACategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements ACategoryService {

    private final ProductMapper productMapper;

    private final TransitionUtils<?, Category, ACategoryVo> categoryT;
    private final TransitionUtils<?, Product, ACategoryVo.ACategoryProduct> productT;

    @Override
    public List<ACategoryVo> getAll() {
        // 获取所有分类, 非禁用，且其下有产品的分类
        List<Category> categories = this.list(
            new LambdaQueryWrapper<Category>()
                .eq(Category::getStatus, true)
                .gt(Category::getProductCount, 0)
        );
        // 获取对应分类的产品，非禁用，库存大于0
        List<String> categoryIds = categories.stream().map(Category::getId).toList();
        List<Product> products = productMapper.selectList(
            new LambdaQueryWrapper<Product>()
                .eq(Product::getStatus, true)
                .in(!categoryIds.isEmpty(), Product::getCategoryId, categoryIds)
                .gt(Product::getStock, 0)
        );
        // 构建 VO
        return categories.stream().map(category -> {
            // 转 VO
            ACategoryVo vo = categoryT.transition(category, ACategoryVo.class);
            // 封装商品
            List<Product> list = products.stream().filter(product -> product.getCategoryId().equals(category.getId())).toList();
            Stream<ACategoryVo.ACategoryProduct> stream = list.stream().map(product -> productT.transition(product, ACategoryVo.ACategoryProduct.class));
            vo.setProducts(stream.toList());
            // 返回
            return vo;
        }).toList();
    }

}
